import { FC, useCallback, useMemo, useState } from 'react';
import { Select, TreeSelect } from 'antd';
import { isArray } from 'lodash';
import { observer } from 'mobx-react';

import RbProTable, { RbProTableStore } from '@components/RbProTable';
import { Content } from '@components/Page';

import {
  COMMON_REQUIRE_RULE,
  COMMON_SELECT_FIELDSNAMES,
  COMPLETELY_FILL_STYLE
} from '@utils/config';
import { Status } from '@enumTypes/enumTypes';
import { generateCommonSelect } from '@utils/renderer';
import { getDeptApi } from '@services/service';
import { TableAlignType } from '@/enumTypes/table';
import request from '@/utils/request';

const store = new RbProTableStore();

const GrantPermission: FC = () => {
  // 字典数据
  const [deptList, setDeptList] = useState<any[]>([]);
  const [userList, setUserList] = useState<any[]>([]);
  const [roleList, setRoleList] = useState<any[]>([]);

  /** 查询部门、用户、角色数据 */
  const handleQueryRulesList = useCallback(() => {
    handlerQueryDeptList();
    handlerQueryUserList();
    handlerQueryRoleList();
  }, []);

  /** 查询部门信息 */
  const handlerQueryDeptList = useCallback(() => {
    store.setSaveLoading(true);
    getDeptApi({ status: Status.enable })
      .then((res: any) => {
        if (res && isArray(res)) {
          setDeptList(res);
        }
      })
      .finally(() => {
        store.setSaveLoading(false);
      });
  }, []);

  /** 查询部门信息 */
  const handlerQueryUserList = useCallback(() => {
    store.setSaveLoading(true);
    request({
      url: '/system/user',
      method: 'GET'
    })
      .then((res: any) => {
        if (res) {
          const { records = [] } = res;
          setUserList(
            records.map((record: any) => ({
              value: record.id,
              option: record.username
            }))
          );
        }
      })
      .finally(() => {
        store.setSaveLoading(false);
      });
  }, []);

  /** 查询角色信息 */
  const handlerQueryRoleList = useCallback(() => {
    store.setSaveLoading(true);
    request({
      url: '/system/role',
      method: 'GET'
    })
      .then((res: any) => {
        if (res) {
          const { records = [] } = res;
          setRoleList(
            records.map((record: any) => ({
              value: record.id,
              option: record.name
            }))
          );
        }
      })
      .finally(() => {
        store.setSaveLoading(false);
      });
  }, []);

  /** 查询条配置列表 */
  const queryFromItems = useMemo(
    () => [
      {
        name: 'deptId',
        label: '部门',
        children: generateCommonSelect(deptList)
      },
      {
        name: 'username',
        label: '用户名',
        children: generateCommonSelect(userList)
      }
    ],
    [deptList, userList]
  );

  /** 表格列配置 */
  const columns = useMemo(
    () => [
      {
        title: '部门名称',
        dataIndex: 'deptName',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '用户',
        dataIndex: 'username',
        align: TableAlignType.center,
        width: 140
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
        align: TableAlignType.center,
        width: '50%'
      }
    ],
    []
  );

  /** 新增表单配置 */
  const addFormItems = useMemo(
    () => [
      {
        name: 'deptId',
        label: '部门',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <TreeSelect
            style={COMPLETELY_FILL_STYLE}
            treeData={deptList}
            fieldNames={{
              value: 'id',
              label: 'name'
            }}
            allowClear
          />
        )
      },
      {
        name: 'userId',
        label: '用户名',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            // mode="multiple"
            options={userList}
          />
        )
      },
      {
        name: 'roleIds',
        label: '角色',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            mode="multiple"
            options={roleList}
          />
        )
      }
    ],
    [deptList, userList, roleList]
  );

  /** 编辑表单配置 */
  const updateFormItems = useMemo(
    () => [
      {
        name: 'deptId',
        label: '部门',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <TreeSelect
            style={COMPLETELY_FILL_STYLE}
            treeData={deptList}
            fieldNames={{
              value: 'id',
              label: 'name'
            }}
            allowClear
          />
        )
      },
      {
        name: 'userId',
        label: '用户名',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            options={userList}
          />
        )
      },
      {
        name: 'roleIds',
        label: '角色',
        rules: [COMMON_REQUIRE_RULE],
        children: (
          <Select
            style={COMPLETELY_FILL_STYLE}
            fieldNames={COMMON_SELECT_FIELDSNAMES}
            mode="multiple"
            options={roleList}
          />
        )
      }
    ],
    [deptList, userList, roleList]
  );

  return (
    <Content>
      <RbProTable
        rowKey="id"
        columns={columns}
        store={store}
        actionUrl="/system/grant"
        sticky
        selectionType
        beforeOpenModalQuery={handleQueryRulesList}
        queryConfig={{
          queryFromItems,
          queryFormat: true
        }}
        addConfig={{ addFormItems }}
        updateConfig={{ updateFormItems }}
        toolBarRender={() => ['add', 'update', 'delete']}
      />
    </Content>
  );
};

export default observer(GrantPermission);
